package com.zsc.newbuds.service.impl;

import com.zsc.newbuds.entity.Admin;
import com.zsc.newbuds.entity.DonationArea;
import com.zsc.newbuds.mapper.DonationAreaMapper;
import com.zsc.newbuds.service.DonationAreaService;
import com.zsc.newbuds.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author D
 */
@Service
public class DonationAreaServiceImpl implements DonationAreaService {

    @Autowired
    DonationAreaMapper donationAreaMapper;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public void addDonationArea(DonationArea donationArea) {
        String key = "list:donationAreaList";
        donationAreaMapper.addDonationArea(donationArea);
        redisUtil.hset(key,donationArea.getDonationAreaId().toString(),donationAreaMapper.getDonationAreaById(donationArea.getDonationAreaId()));
    }

    @Override
    public List<DonationArea> getDonationAreaList() {
        List<DonationArea> donationAreas = new ArrayList<>();
        String key = "list:donationAreaList";
        if(redisUtil.hasKey(key)){
            Map<Object, Object> map = redisUtil.hmget(key);
            for(Map.Entry<Object, Object> donationArea:map.entrySet()){
                donationAreas.add((DonationArea) donationArea.getValue());
            }
        }else {
            System.out.println("从数据库中获取workList");
            Map< String,Object> map = new HashMap<>();
            donationAreas = donationAreaMapper.getDonationAreaList();
            for (DonationArea donationArea : donationAreas){
                map.put(donationArea.getDonationAreaId().toString(),donationArea);
            }
            redisUtil.hmset(key,map);
        }
        return donationAreas;
    }

    @Override
    public void updateTimes(Integer id) {
        String key = "list:donationAreaList";
        DonationArea donationArea = (DonationArea) redisUtil.hget(key,id.toString());
        int times = donationArea.getDonationAreaTimes() + 1;
        donationAreaMapper.updateTimes(id,times);
        redisUtil.hset(key,id.toString(),donationAreaMapper.getDonationAreaById(id));
    }


}
